<script setup>
import './flexible.js'


import {ref, onMounted, nextTick} from 'vue';

import china from '@/json/china.json'

import * as echarts from 'echarts';

import {
  getCollegeStudent,
  getStudentGender,
  getStudentProvince,
  getNumber,
  getStudentHobby
} from "@/views/student/analysis.js";
import {getCityPositionByName} from './cityPostion.js'

const collegeNameList = ref([]);
const collegeNumberList = ref([]);

const chart1 = ref(null);
const chart2 = ref(null);

const hobbyList = ref([])
const hobbyCount = ref([])
const getHobby = async () => {
  const res = await getStudentHobby()
  hobbyList.value = res.data.data.name.split(",")
  hobbyCount.value = res.data.data.count.split(",")
  //拿到hobby的数据
  console.log(hobbyList.value)
  console.log(hobbyCount.value)
  await nextTick(() => {
    getEcharts();
  });
}


//模拟数据
const mockData = ref([])

const getmokcData = async () => {
  const res = await getStudentProvince();
  mockData.value = res.data.data
  await nextTick(() => {
    getEcharts3();
  });
}
const stNumber = ref({})
const getNumbers = async () => {
  const res = await getNumber()
  stNumber.value = res.data.data;

}

const getEcharts = () => {
  let initMap = echarts.init(document.querySelector('#hobbyRef'))
  const option = {
    color:['#cb781a','#0a1548','#42b883'],
    title: {
      text: '学生兴趣爱好',
      left: 'center',
      textStyle: {
        color: '#2f89cf', // 设置标题颜色为红色
        fontSize: 18, // 设置字体大小
        fontWeight: 'bold' // 设置字体粗细
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      }
    },
    // legend: {},
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: hobbyList.value,
      // 调整y轴的字体
      axisLabel: {
        fontSize: 10, // 设置Y轴标签的字体大小
        interval: 0,  // 强制显示所有标签
        // rotate: 45    // 如果分类数据太多，可以旋转标签以避免重叠
        color:'#f2c55c'
      }
    },
    series: [
      {
        name: '兴趣爱好',
        type: 'bar',
        data: hobbyCount.value.map((count, index) => ({
          value: count,
          itemStyle: { color: ['#cb781a', '#eeeeee', '#42b883'][index % 3] } // 每个柱条设置不同颜色
        }))
      }
    ]
  };
  initMap.setOption(option)
}

/**
 * 地图模块的echarts
 * @returns {*}
 */

const getEcharts3 = () => {
  //拿到初始化
  let initMap = echarts.init(document.querySelector('#mapDom'));
  //注册中国国地图
  echarts.registerMap('china', china);

  //拿到前五的数据
  let topFiveData = mockData.value.sort((a, b) => b.value - a.value).slice(0, 5);
  // 将筛选后的数据转换为 ECharts 需要的格式
  let data = topFiveData.map(i => {
    let cityPosition = getCityPositionByName(i.name);
    return {
      name: i.name,
      value: cityPosition ? [...cityPosition.value.map(Number), i.value] : [0, 0, i.value]
    };
  });
  // 创建一个方便查找的字典对象
  let mockDataMap = mockData.value.reduce((acc, item) => {
    acc[item.name] = item.value;
    return acc;
  }, {});

  let options = {
    title: {
      text: '学生家乡分布',
      left: 'center',
      textStyle: {
        color: '#fa4c27',
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        // 从 mockDataMap 中获取对应省份的数据值
        let count = mockDataMap[params.name] || 0; // 确保显示为0而不是NaN
        return `${params.name}<br/>${count} (学生总数)`;
      }
    },
    toolbox: {
      show: true,
      orient: 'vertical',
      left: 'right',
      top: 'center',
      feature: {
        dataView: {readOnly: false, title: '数据视图'},
        restore: {title: '还原'},
        saveAsImage: {title: '保存为图片', pixelRatio: 2}
      }
    },
    visualMap: {
      min: 0,
      max: Math.max(...topFiveData.map(d => d.value)),
      text: ['High', 'Low'],
      realtime: false,
      calculable: true,
      inRange: {
        color: ['#e0f7fa', '#80deea', '#0288d1']
      }
    },
    geo: {
      map: 'china',
      roam: false,
      // zoom: 1, // 调整这个值来放大地图
      label: {
        show: false
      },
      emphasis: {
        label: {
          show: false
        }
      }
    },
    series: [
      {
        name: '中国',
        type: 'map',
        map: 'china',
        label: {
          show: false
        },
        data: mockData.value,
      },
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        symbol: 'pin',
        symbolSize: [50, 50],
        label: {
          show: true,
          color: '#fff',
          formatter(value) {
            return value.name + value.data.value[2]; // 显示人数
          },
          fontSize: 10
        },
        itemStyle: {
          color: '#e30707' // 标记颜色
        },
        data: data,
      }
    ]
  };

  initMap.setOption(options);

};


const getClothesData = async () => {
  const res = await getCollegeStudent();
  collegeNameList.value = res.data.data.nameList.split(',');
  collegeNumberList.value = res.data.data.numberList.split(',');
  console.log(collegeNameList.value);
  console.log(collegeNumberList.value);

  // 确保数据加载完成后，初始化图表
  await nextTick(() => {
    getEcharts1();
  });
}

const sexData = ref([])
const than = ref('')
const getSex = async () => {
  const res = await getStudentGender();
  sexData.value = res.data.data
  than.value = sexData.value[1].value + ':' + sexData.value[0].value
  // console.log(sexData.value)
  await nextTick(() => {
    getEcharts2();
  });
}

/**
 * 学院人数可视化
 */
const getEcharts1 = () => {
  const chartOptions = {
    grid: {
      left: '0%',
      right: '0%',
      top: "20%",
      bottom: '4%',
      containLabel: true
    },
    // 设置标题
    title: {
      // 标题
      text: '学院人数排名前五',
      //居中位置
      left: 'center',
      //设置标题的样式
      textStyle: {
        color: '#2f89cf', // 设置标题颜色为红色
        fontSize: 18, // 设置字体大小
        fontWeight: 'bold' // 设置字体粗细
      }
    },
    color: ['#2f89cf'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {type: 'shadow'}
    },
    xAxis: {
      type: 'category',
      data: collegeNameList.value,
      axisTick: {
        alignWithLabel: true
      },
      //修改
      axisLabel: {
        color: "rgba(255,255,255,.6)",
        fontSize: 12, // 调大字体大小
        interval: 0, // 强制显示所有标签
        rotate: 30, // 旋转标签以避免重叠
        formatter: function (value) {
          // 如果名称超过10个字符，显示省略号
          return value.length > 10 ? value.slice(0, 10) + '...' : value;
        }
      },
      axisLine: {
        show: false,
        // 如果想要设置单独的线条样式
        lineStyle: {
          color: "rgba(255,255,255,.1)",
          width: 1,
          type: "solid"
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: "rgba(255,255,255,.6)",
        fontSize: "12"
      },
      // y轴线条样式
      axisLine: {
        lineStyle: {
          color: "rgba(255,255,255,.1)",
          // width: 1,
          // type: "solid"
        }
      },
      // y 轴分隔线样式
      splitLine: {
        lineStyle: {
          color: "rgba(255,255,255,.1)"
        }
      }
    },
    series: [{
      name: '学生数量',
      type: 'bar',
      barWidth: '35%',
      data: collegeNumberList.value,
      itemStyle: {
        barBorderRadius: 5
      }
    }]
  };
  let instance = echarts.init(chart1.value);
  instance.setOption(chartOptions);
}
/**
 * 性别的可视化
 */
const getEcharts2 = () => {
  const option = {
    grid: {
      left: '0%',
      right: '0%',
      top: "20%",
      bottom: '0%',
      containLabel: true
    },
    color: ['pink', '#2f89cf'], // 自定义颜色
    title: {
      text: `男女性别比例${than.value}`,
      left: 'center',
      textStyle: {
        color: '#2f89cf', // 设置标题颜色为红色
        fontSize: 18, // 设置字体大小
        fontWeight: 'bold' // 设置字体粗细
      }
    },

    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        color: '#2f89cf', // 设置标题颜色为红色
        fontSize: 18, // 设置字体大小
        fontWeight: 'bold' // 设置字体粗细
      }
    },
    series: [
      {
        name: '性别人数',
        type: 'pie',
        radius: '50%',
        data: sexData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  let instance2 = echarts.init(chart2.value);
  instance2.setOption(option);
}
onMounted(() => {

  // getEcharts3()
  getmokcData()
  getClothesData();
  getSex();
  getNumbers();
  getHobby();
})
</script>
<template>
  <div class="header">
    <h1>工程数据分析</h1>
    <div class="showTime"></div>
  </div>
  <!-- 页面主体  一个大的盒子  划分 -->
  <div class="mainbox">
    <div class="column">
      <div class="panel bar" ref="chart1">
        <div class="chart"></div>
        <!--        <h2 style="color: red">学院人数排名前五</h2>-->
        <div class="panel-footer"></div>
      </div>
      <div class="panel line" ref="chart2">
        <div class="chart"></div>
        <h2>标题</h2>
        <div class="panel-footer"></div>
      </div>
      <div class="panel pie">
        <h2></h2>
        <div class="panel-footer"></div>
      </div>
    </div>


    <div class="column">
      <div class="no">
        <div class="no-hd">
          <ul>
            <li>{{ stNumber.numberTeacher }}</li>
            <li>{{ stNumber.numberStudent }}</li>
          </ul>
        </div>
        <div class="no-bd">
          <ul>
            <li>学生人数</li>
            <li>老师人数</li>
          </ul>
        </div>
      </div>
      <!-- 地图模块 -->
      <div class="map">
        <!-- 放到map中间 -->
        <div class="chart" id="mapDom"></div>
        <div class="map1"></div>
        <div class="map2"></div>
        <div class="map3"></div>
      </div>
    </div>


    <div class="column">

      <div class="panel bar" >
        <h2></h2>
        <div class="chart" id="hobbyRef"></div>
        <div class="panel-footer"></div>
      </div>
      <div class="panel line">
        <h2></h2>

        <div class="panel-footer"></div>
      </div>
      <div class="panel pie">
        <h2></h2>
        <div class="panel-footer"></div>
      </div>

    </div>
  </div>
</template>

<style scoped lang="less">
@import "./index";
</style>
